package com.sky.service.user.impl;

import com.sky.service.user.PrePayUrlNotifyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @author zgp
 * @version V1.0
 * @date 2025-02-03 19:06
 */
@Slf4j
@Service
public class PrePayUrlNotifyServiceImpl implements PrePayUrlNotifyService {

    // 使用线程安全的列表来保存所有的SseEmitter连接
    private final CopyOnWriteArrayList<SseEmitter> emitters = new CopyOnWriteArrayList<>();

    @Override
    public void saveNotify(String message) {
        for (SseEmitter emitter : emitters) {
            try {
                emitter.send(SseEmitter.event().data(message));
            } catch (IOException e) {
                log.error("推送预支付url失败，{}", e.getMessage(), e);
                throw new RuntimeException(e);
            }
        }
    }

    @Override
    public SseEmitter pushNotify() {
        SseEmitter emitter = new SseEmitter();
        emitters.add(emitter);

        // 客户端完成或超时时，移除连接
        emitter.onCompletion(() -> emitters.remove(emitter));
        emitter.onTimeout(() -> emitters.remove(emitter));

        return emitter;

    }
}
